using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Wheels.Controllers
{
    public class UserController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login()
        {
            return View(new LoginInfo());
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult OpenIdLogin()
        {
            return View("OpenIdLogin");
        }

/*        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Registration()
        {
            var user = new User();
            var loginInfo = new LoginInfo(Request);

            if((Session["RegistrationInfo"]) != null)
            {
                user = ((User)Session["RegistrationInfo"]);
            }
            else if (loginInfo.Login != String.Empty)
            {
                using (var service = new CleverServiceClient())
                {
                    var data = service.getUser(loginInfo.Login);
                    if (data != null && data.Password == loginInfo.Password)
                    {
                        Session.Add("RegistrationInfo", data);
                        user = data;
                    }
                }
            }
            ViewData["NewPassword"] = "";
            ViewData["ConfirmNewPassword"] = "";

            return View(user);
        }
        */
/*        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string login, string password)
        {
            if (login.Trim().Length == 0)
            {
                ModelState.AddModelError("login", "Login is empty");
            }
            if (password.Trim().Length == 0)
            {
                ModelState.AddModelError("password", "Password is empty");
            }
            string passMD5 = LoginInfo.calculateMD5Hash(password);

            if (ModelState.IsValid)
            {
                using (var service = new CleverServiceClient())
                {
                    var user = service.getUser(login);
                    if (user == null || !user.Password.Equals(passMD5))
                    {
                        ModelState.AddModelError("login", "invalid data");
                    }
                    else
                    {
                        Session["RegistrationInfo"] = user;
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return View("Login", new LoginInfo(login, ""));
            }

            var info = new LoginInfo(login, passMD5);
            info.Save(Response);

            return View("Message", (object)"Successfully logged in");
        }
*/

        public ActionResult Message(string msg)
        {
            return View(msg);
        }


/*        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Registration(int id, FormCollection collection)
        {
            var user = new User();
            user.Id = id;
            user.Login = collection["login"];
            
            if ((!String.IsNullOrEmpty(collection["NewPassword"]) ||  
                !String.IsNullOrEmpty(collection["ConfirmNewPassword"])) &&
                collection["NewPassword"] == collection["ConfirmNewPassword"] )
            {
                user.Password = LoginInfo.calculateMD5Hash(collection["NewPassword"]);            
            }
            else if ((!String.IsNullOrEmpty(collection["NewPassword"]) ||
                !String.IsNullOrEmpty(collection["ConfirmNewPassword"])))
            {
                ModelState.AddModelError("NewPassword", "Passwords did not match");
            }
            else
            {
                ModelState.AddModelError("NewPassword", "Required field");
            }
            ViewData["NewPassword"] = collection["NewPassword"];
            ViewData["ConfirmNewPassword"] = collection["ConfirmNewPassword"];

            if (collection["FirstName"].Trim().Length == 0)
            {
                ModelState.AddModelError("FirstName", "Required field");
            }
            if (collection["Surname"].Trim().Length == 0)
            {
                ModelState.AddModelError("Surname", "Surname is required.");
            }
            if (collection["Address"].Trim().Length == 0)
            {
                ModelState.AddModelError("Address", "Address is required.");
            }
            if ((collection["Zipcode"].Trim().Length > 0) && (!Regex.IsMatch(collection["Zipcode"], @"^\d{5}$|^\d{5}-\d{4}$")))
            {
                ModelState.AddModelError("Zipcode", "Zipcode is invalid.");
            }
            if (!Regex.IsMatch(collection["Phone"], @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
            {
                ModelState.AddModelError("Phone", "Phone number is invalid.");
            }
            if (!Regex.IsMatch(collection["Email"], @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
            {
                ModelState.AddModelError("Email", "Email format is invalid.");
            }

            user.Firstname = collection["FirstName"].Trim();
            user.Lastname = collection["Surname"].Trim();
            user.Email = collection["Email"].Trim();
            user.Phone = collection["Phone"].Trim();
            user.Address = collection["Address"].Trim();
            user.Zip = collection["Zipcode"].Trim();

            if (!ModelState.IsValid)
            {
                return View("Registration", user);
            }

            OperationResultOfUserNYQO2XZG result;
            using (var service = new CleverServiceClient())
            {
                if(user.Id != 0)
                {
                    result = service.UpdateUser(user);
                }
                else
                {
                    result = service.CreateUser(user);
                }
            }

            if(result.Code > 0)
            {
                ModelState.AddModelError("Login", result.Message);
                return View("Registration", user);
            }

            Session.Add("RegistrationInfo", result.Entity);
            return View("Message", (object)"User data saved");
        }
        */

        public ActionResult Authenticate()
        {
            var info = new LoginInfo(Request);
            if (info.Login != String.Empty)
            {
                return Json(true);
            }

            return Json(false);
        }
    }

    public class LoginInfo
    {
        public LoginInfo()
        {
            Login = String.Empty;
            Password = String.Empty;
        }

        public LoginInfo(string login, string password)
        {
            Login = login;
            Password = password;
        }

        public LoginInfo(HttpRequestBase request)
        {
            Login = String.Empty;
            Password = String.Empty;

            HttpCookie cookie = request.Cookies["LoginInfo"];
            if (cookie != null && !String.IsNullOrEmpty(cookie.Value))
            {
                string[] values = cookie.Value.Split('#');
                if (values.Length == 2)
                {
                    Login = values[0];
                    Password = values[1];
                }
            }
        }

        public String Login { get; set; }
        public String Password { get; set; }

        public override string ToString()
        {
            return String.Format("{0}#{1}", Login, Password);
        }

        public void Save(HttpResponseBase response)
        {
            var cookie = new HttpCookie("LoginInfo");
            cookie.Expires = DateTime.Now.AddYears(1);
            cookie.Value = ToString();
            response.SetCookie(cookie);
        }

        public static string calculateMD5Hash(string value)
        {
            var cryptoService = new MD5CryptoServiceProvider();
            byte[] resultBytes = cryptoService.ComputeHash(Encoding.Default.GetBytes(value));
            var sBuilder = new StringBuilder();
            for (int i = 0; i < resultBytes.Length; i++)
            {
                sBuilder.Append(resultBytes[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }
    }
}